﻿using K9Nano.Application.Authentication;
using K9Nano.Domain.Authentication;
using K9Nano.Domain.Caching;
using K9Nano.Domain.Entities;
using K9Nano.Exceptions;
using K9Nano.Session;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace K9Nano.AspNetCore.Controllers;

[Route("api/account")]
[Authorize]
public abstract class AccountControllerBase<TUser, TRole, TUserManager>(IUserCache cache, IUserContextAccessor accessor, TUserManager userManager) : ApiControllerBase
    where TUserManager : IUserManager<TUser, TRole>
    where TUser : UserBase
    where TRole : RoleBase
{
    [HttpGet("userInfo")]
    public virtual AccountDto? GetCurrnetUser()
    {
        var userId = accessor.CurrentUser?.UserId;
        if (userId > 0)
        {
            var user = cache.GetUser(userId.Value);
            if (user is not null)
            {
                string? orgName = null;
                if (user.OrganizationId > 0)
                {
                    orgName = HttpContext.RequestServices.GetRequiredService<IOrganizationUnitCache>()
                        .Get(user.OrganizationId.Value)?.DisplayName;
                }
                return new AccountDto(user.Id, user.Username, user.Name, user.Roles, user.Permissions, user.OrganizationId, orgName);
            }
        }
        return null;
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    [HttpPut("password")]
    public virtual async Task<ApiResponse> ChangePassword(ChangePasswordDto dto)
    {
        var userId = accessor.CurrentUser?.UserId;
        if(userId is null)
        {
            return ApiResponse.BadRequest("请完成用户认证");
        }

        return await userManager.ChangePasswordAsync(userId.Value, dto.OldPassword, dto.NewPassword, HttpContext.RequestAborted);
    }
}

